import React, { useEffect, useState } from 'react';
import styles from './index.less';
import { Spin, Image, message } from 'antd';
import { connect } from 'dva';
import moment from 'moment';
import FormOutlined from '@ant-design/icons/FormOutlined';
import EyeOutlined from '@ant-design/icons/EyeOutlined';
import DownloadOutlined from '@ant-design/icons/DownloadOutlined';
import { TRDefault } from '@/components';
import cls from 'classnames';
import _ModalAlert from './modal';
import { queryFlairList } from '@/services/user';
import { AlertResult, HttpCode } from '@/utils/contacts';

function QualificationInfoComp(props) {
  const column = [
    {
      title: '高处作业证',
      id: 'WORKING_AT_HEIGHTS',
    },
    {
      title: '高压电工证',
      id: 'HIGH_VOLTAGE_ELECTRICIAN',
    },
    {
      title: '低压电工证',
      id: 'LOW_VOLTAGE_ELECTRICIAN',
    },
  ];
  const [state, setState] = useState({
    loading: true,
    data: [],
  });

  useEffect(() => {
    feachData();
  }, []);

  const feachData = async () => {
    let id = props.currentUser?.personId;
    if (!id) return message.error('系统错误');
    setState({ loading: true });
    let res = await queryFlairList({ id });
    if (res?.statusCode === HttpCode.SUCCESS) {
      setState({
        loading: false,
        data: res.data || [],
      });
    } else {
      message.error(res?.message || '请求失败');
      setState({ loading: false });
    }
  };

  const handleOption = async (n, item) => {
    let res = await _ModalAlert.show({
      ...n,
      personId: props.currentUser?.personId,
      initValue: item,
    });
    if (res?.index === AlertResult.SUCCESS) {
      feachData();
    }
    _ModalAlert.dismiss();
  };

  const downloadFile = (item) => {
    try {
      const linkElement = document.createElement('a');
      linkElement.style.display = 'none';
      const openUrl = item.filePath;
      linkElement.href = openUrl;
      document.body.appendChild(linkElement);
      linkElement.click();
      document.body.removeChild(linkElement);
    } catch (e) {
      Alert.error('下载失败');
    }
  };

  const dayRender = (type, date) => {
    return Math.abs(moment(new Date().toLocaleDateString()).diff(moment(date), 'days'))
      .toString()
      .split('')
      .map((i, index) => {
        return (
          <span
            className={cls({
              [styles.date]: true,
              [styles[type]]: true,
            })}
            key={index + ''}
          >
            {i}
          </span>
        );
      });
  };
  const contentRender = () => {
    return column.map((n, i) => {
      let item = state.data?.filter((m) => m.flairCode == n.id)[0] || {};
      if (item.leftFileId) {
        item.files = [
          {
            id: item.leftFileId,
            fileName: item.leftFileName,
            filePath: item.leftFilePath,
          },
        ];
      }
      if (item.rightFileId) {
        item.files = (item.files || []).concat([
          {
            id: item.rightFileId,
            fileName: item.rightFileName,
            filePath: item.rightFilePath,
          },
        ]);
      }
      return (
        <div className={styles.contentItem} key={n.id}>
          <div className={styles.infoBox}>
            <div className={styles.title}>{n.title}</div>
            <div className={styles.subBox}>
              <div>
                <div className={styles.subTitle}>复审日期</div>
                <div className={styles.subInfoBox}>
                  <div>{item.reviewTime ? moment(item.reviewTime).format('YYYY-MM-DD') : '-'}</div>
                  {item.reviewTime ? (
                    item.overdue == '0' ? (
                      <div className={styles.tip}>
                        复审超期
                        <span className={styles.dateBox}>
                          {dayRender('dateOverdue', item.reviewTime)}
                        </span>
                        天
                      </div>
                    ) : (
                      <div className={styles.tip}>
                        距离复审还有
                        <span className={styles.dateBox}>
                          {dayRender('dateNotOverdue', item.reviewTime)}
                        </span>
                        天
                      </div>
                    )
                  ) : null}
                </div>
              </div>
              <div>
                <div className={styles.subTitle}>有效期</div>
                <div className={styles.subInfoBox}>
                  <div>
                    {item.effectiveTime ? moment(item.effectiveTime).format('YYYY-MM-DD') : '-'}
                  </div>
                  {item.effectiveTime ? (
                    item.effective == '0' ? (
                      <div className={styles.tip}>
                        证件已超期
                        <span className={styles.dateBox}>
                          {dayRender('dateOverdue', item.effectiveTime)}
                        </span>
                        天
                      </div>
                    ) : (
                      <div className={styles.tip}>
                        距离到期还有
                        <span className={styles.dateBox}>
                          {dayRender('dateNotOverdue', item.effectiveTime)}
                        </span>
                        天
                      </div>
                    )
                  ) : null}
                </div>
              </div>
            </div>
          </div>
          <div className={styles.filesBox}>
            {item.files?.length ? (
              item.files.map((it) => {
                return (
                  <div className={styles.filesItem} key={it.id}>
                    <Image
                      src={it.filePath}
                      width={310}
                      height={180}
                      preview={{
                        mask: (
                          <div className={styles.maskBox}>
                            <div className={styles.preview}>
                              <EyeOutlined className={styles.icon} />
                              <div>预览</div>
                            </div>
                            <div
                              className={styles.download}
                              onClick={(e) => {
                                e.stopPropagation();
                                downloadFile(it);
                              }}
                            >
                              <DownloadOutlined className={styles.icon} />
                              <div>下载</div>
                            </div>
                          </div>
                        ),
                      }}
                    />
                  </div>
                );
              })
            ) : (
              <div className={styles.mepty}>
                <TRDefault type="emptysm" message="暂未添加" />
              </div>
            )}
          </div>
          <div className={styles.buttonBox}>
            <div className={styles.button} onClick={() => handleOption(n, item)}>
              <FormOutlined />
              <span>编辑</span>
            </div>
          </div>
        </div>
      );
    });
  };

  return (
    <Spin spinning={state.loading}>
      <div className={styles.qualificationInfoBox}>
        <div className={styles.header}>
          <div className={styles.title}>资质信息</div>
        </div>
        <div className={styles.content}>{contentRender()}</div>
      </div>
    </Spin>
  );
}

export default connect(({ user }) => ({
  currentUser: user.currentUser,
}))(QualificationInfoComp);
